package com.example.controller;

import com.example.constants.Constants;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("confirm")
public class ConfirmController {
    /**
     * 注入 RabbitTemplate 模板对象
     */
    @Resource
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("test/{name}")
    public String send(@PathVariable("name") String name) {

        /**
         * 发送消息
         */
        String str = name + "\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS").format(new Date());

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(Constants.MY_FANOUT_EXCHANGE, "", str, correlationData);

        try {
            /**
             * 睡眠,程序还没运行结束
             * 确认回调已经执行,说明是异步的
             */
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("消息发送成功!\t" + str);
        return "success";
    }

    /**
     * 测试失败
     *
     * @param name
     * @return
     */
    @RequestMapping("test-fail/{name}")
    public String sendFail(@PathVariable("name") String name) {
        String str = name + "\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS").format(new Date());

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        String errorExchangeName = Constants.MY_FANOUT_EXCHANGE + "abc";
        rabbitTemplate.convertAndSend(errorExchangeName, "", str, correlationData);

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("消息发送成功!\t" + str);
        return "success";
    }
}
